import { memo, useState, useTransition } from 'react'
import classnames from 'classnames'

enum TabKeyEnums {
  Tab1 = 1,
  Tab2 = 2
}
export default function TransitionDemo() {
  const [isPending, startTransition] = useTransition();
  const [tabKey, setTabKey] = useState<TabKeyEnums>(TabKeyEnums.Tab1);

  function handleClick(tab: TabKeyEnums) {
    startTransition(() => {
      setTabKey(tab);
    })
  }

  function getTabClassnames(tab: TabKeyEnums) {
    return classnames(
      'hover:text-white p-2 rounded hover:bg-blue-200 cursor-pointer',
      {
        'bg-blue-200': tab === tabKey
      }
    )
  }

  function renderTabContent() {
    switch(tabKey) {
      case TabKeyEnums.Tab1:
        return <div>Tab1</div>
      case TabKeyEnums.Tab2:
        return <PostsTab />
      default:
        return <div>Tab1</div>
    }
  }

  return (
    <div>
      <h3 className="font-bold">过渡更新 transition </h3>

      <div className="p-4">
        <h4 className='font-bold'>DEMO1：Tab页切换卡顿问题</h4>
        <input type='number' className='border focus-visible:outline-none focus-visible:border-orange-300'></input>
        <div className="flex space-x-1">
          <div className={getTabClassnames(TabKeyEnums.Tab1)} onClick={() => handleClick(TabKeyEnums.Tab1)} >Tab1</div>
          <div className={getTabClassnames(TabKeyEnums.Tab2)} onClick={() => handleClick(TabKeyEnums.Tab2)} >Tab2</div>
        </div>
        <div className="p-4 relative min-h-[400px] bg-gray-200">
          { isPending && <div className='absolute left-0 top-0 w-full h-full bg-neutral-400 flex items-center justify-center'>loading...</div> }
          { renderTabContent() }
        </div>
      </div>
    </div>
  )
}

const PostsTab = memo(() => {
  let items = [];
  for (let i = 0; i < 500; i++) {
    items.push(<SlowPost key={i} index={i} />);
  }
  return <ul className='h-[500px] overflow-scroll'>{items}</ul>;
});
 
const SlowPost = ({ index }: { index: number }) => {
  let startTime = performance.now();
  while (performance.now() - startTime < 10) { }
  return <li>Post on weijunext.com #{index + 1}</li>;
};